package com.qxgl.qxglt.service;


import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.qxgl.qxglt.dao.IModulesDao;
import com.qxgl.qxglt.dao.IRolesDao;
import com.qxgl.qxglt.dto.RolesDTO;
import com.qxgl.qxglt.model.Modules;
import com.qxgl.qxglt.model.Roles;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class RolesServiceImpl implements IRolesService {

    @Resource
    private IRolesDao rolesDao;
    @Resource
    private IModulesDao modulesDao;
    @Override
    public Page<Roles> findPage(RolesDTO dto) {
        Sort sort = Sort.by(Sort.Order.asc("id"));
        Pageable page = PageRequest.of((dto.getPage() - 1) * dto.getLimit(), dto.getLimit(), sort);
        return rolesDao.findAll(getWhereClause(dto), page);
    }

    private Specification<Roles> getWhereClause(RolesDTO dto) {
        return new Specification<Roles>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Roles> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate p = criteriaBuilder.conjunction();
                List<Expression<Boolean>> exlList = p.getExpressions();
                if (dto.getName() != null && "".equals(dto.getName())) {
                    exlList.add(criteriaBuilder.equal(root.<String>get("name"), "%" + dto.getName() + "%"));
                }
                return p;
            }

        };
    }

    @Override
    public void setModules(String role_id, List<String> moduleslist) {
        Roles roles = rolesDao.getOne(role_id);
        for (String modulesId : moduleslist) {
            Modules modules = new Modules();
            modules.setId(modulesId);
            roles.getModulesList().add(modules);
        }
        rolesDao.save(roles);
    }


}